package org.hxzon.tapestry5.components;

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;

public class ZkComponents {
    public static final String Attribute_TCompResources = "tCompResources";
    public static final String Attribute_TCompId = "tCompId";
    @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL)
    private String zulFile;

//    @Inject
//    private RequestGlobals requestGlobals;

    @Inject
    private ComponentResources resources;
    @Inject
    private HttpServletRequest request;
    @Inject
    private HttpServletResponse response;

    boolean setupRender(MarkupWriter writer) throws ServletException, IOException {
//        HttpServletRequest request = requestGlobals.getHTTPServletRequest();
//        HttpServletResponse response = requestGlobals.getHTTPServletResponse();

        request.setAttribute(Attribute_TCompResources, resources);
        request.setAttribute(Attribute_TCompId, resources.getId());

        CharResponseWrapper body = new CharResponseWrapper(response);
        request.getRequestDispatcher("/" + zulFile + ".zul").include(request, body);
        writer.writeRaw(body.toString());
        return true;
    }

    public class CharResponseWrapper extends HttpServletResponseWrapper {
        private CharArrayWriter output;

        public CharResponseWrapper(HttpServletResponse response) {
            super(response);
            output = new CharArrayWriter();
        }

        public PrintWriter getWriter() {
            return new PrintWriter(output);
        }

        public String toString() {
            return output.toString();
        }
    }
}
